package com.example.diemtinvietnam;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;



import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.annotation.SuppressLint;
import android.util.Log;
import android.util.JsonReader;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class jsonParse {
	   
	   private String id = "id";
	   private String title = "title";
	   private String date = "date";
	   private String image = "image";
	   private String link = "link";
	   private String source = "maindomain";	   
	   private String urlString = null;
	   public volatile boolean parsingComplete = true;
	   public ArrayList<HashMap<String, String>> itemNewsList;
	   
	   public jsonParse(String url){
	      this.urlString = url;
	   }
	   public String getTitle(){
	      return title;
	   }
	   public String getImage(){
	      return image;
	   }
	   public ArrayList<HashMap<String, String>> getItemNewsList(){
		   return itemNewsList;
	   }
	   
	   @SuppressLint("NewApi")
	   public void readAndParseJSON(String in) {
		  JSONArray items = null; 
	      try {
	    	  JSONObject jsonObj = new JSONObject(in);
              
              // Getting JSON Array node
	    	  items = jsonObj.getJSONArray("news");	    	  
	    	  Log.e("items.length", String.valueOf(items.length()));
	    	  itemNewsList = new ArrayList<HashMap<String, String>>();
              // looping through All Contacts
              for (int i = 0; i < items.length(); i++) {
                  JSONObject c = items.getJSONObject(i);
                   
                  title = c.getString(MainActivity.KEY_TITLE);
                  image = c.getString(MainActivity.KEY_IMAGE); 
                  link=c.getString(MainActivity.KEY_LINK); 
                  source=c.getString(MainActivity.KEY_SOURCE); 
                  date=c.getString(MainActivity.KEY_DATE);
                  Log.e("title", title);
                  Log.e("image", image);	
                  Log.e("link", link);
                  // tmp hashmap for single contact
                  HashMap<String, String> itemDetail = new HashMap<String, String>();

                  // adding each child node to HashMap key => value
                  itemDetail.put(MainActivity.KEY_TITLE, title);
                  itemDetail.put(MainActivity.KEY_IMAGE, image);
                  itemDetail.put(MainActivity.KEY_LINK, link);
                  itemDetail.put(MainActivity.KEY_SOURCE, source);
                  itemDetail.put(MainActivity.KEY_DATE, date);
                  Log.e("itemDetail.put", "itemDetail.put");
                  // adding contact to contact list
                  itemNewsList.add(itemDetail);
              }
	         parsingComplete = false;



	        } catch (Exception e) {
	           // TODO Auto-generated catch block
	           e.printStackTrace();
	        }

	   }
	   public void fetchJSON(){
	      Thread thread = new Thread(new Runnable(){
	         @Override
	         public void run() {
	         try {
	            URL url = new URL(urlString);
	            Log.e("fetchJSON", urlString);
	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	            conn.setReadTimeout(10000 /* milliseconds */);
	            conn.setConnectTimeout(15000 /* milliseconds */);
	            conn.setRequestMethod("GET");
	            conn.setDoInput(true);
	            //conn.setRequestProperty(field, newValue)
	            // Starts the query
	            conn.connect();
	            Log.e("fetchJSON", "ok1");
		         //InputStream stream = conn.getInputStream();
	            InputStreamReader reader = null;
		         StringBuilder builder = new StringBuilder();
	
		         try {
		             // ...
		             reader = new InputStreamReader(conn.getInputStream(), "UTF-8");
		             char[] buffer = new char[8192];
	
		             for (int length = 0; (length = reader.read(buffer)) > 0;) {
		                 builder.append(buffer, 0, length);
		                 
		             }
		         } finally {
		             if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
		         }
	
		         String html = builder.toString();
		         
		         String data = html;//convertStreamToString(stream);
	      		 data="{\"news\":"+data+"}";
	      		 Log.e("fetchJSON", data);
	      		 readAndParseJSON(data);
	      		 //stream.close();

	         } catch (Exception e) {
	            e.printStackTrace();
	         }
	         }
	      });

	       thread.start(); 		
	   }
	   static String convertStreamToString(java.io.InputStream is) {
	      java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
	      return s.hasNext() ? s.next() : "";
	   }
}
